package show.hkl.code_migrate.parser;

import show.hkl.code_migrate.project.ReadProjectFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.IntStream;

/**
 * <p>
 * 简单的Java文件分析
 *
 * @author hkl
 * @version 1.0
 * @date 2021/3/18 19:40
 * </p>
 */
public class SimpleJavaParser implements Parser {

    @Override
    public String getCurrentParserName() {
        return "java";
    }

    public static void main(String[] args) {
        SimpleJavaParser simpleJavaParser = new SimpleJavaParser();

        String path = "E:\\workspace\\project\\tools\\code-migrate\\src\\main\\java\\show\\hkl\\code_migrate\\parser\\Test.java";
        File file = new File(path);
        simpleJavaParser.parser(file);
    }


    /**
     * 分析核心
     *
     * @param file
     * @return
     */
    public String parser(File file) {

        try {
            List<String> in = Files.readAllLines(Paths.get(file.toURI()));
            // 解析方法
            parserMethods(in);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "";
    }


    public static final void parserMethods(List<String> lines) {
        ListIterator<String> iterator = lines.listIterator();

        String methodRegexPattern = "(public|protected|private)( static)?( final)?( \\S+)( \\S+)( ?\\(\\s?.+).+[^;]$";

        boolean onOff = false; // 方法开关
        int counter = 0; // 计数器
        Deque<String> stack = new LinkedList();// 方法栈

        while (iterator.hasNext()) {
            String line = iterator.next().trim();
            boolean matches = line.matches(methodRegexPattern);

            // 如果该行是方法，打开开关
            if (matches) {
                onOff = true;
            }

            // 判断开关是否打开，像流一样。开关后面的到”}“都会被放入栈中
            if (onOff) {
                stack.push(line);

                // 思路:来自栈的应用，括号匹配应用
                if (line.contains("{")) {
                    counter++;
                } else if (line.contains("}")) {
                    counter--;
                }

            }

            // 判断计数器是否为0
            if (counter == 0) {
                onOff = false;
            }
        }
        System.out.println(stack);
    }
}
